package org.an.demo.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import org.an.demo.R;
import org.an.ku.util.DensityUtil;

/**
 * 自定义TextView 默认添加5dp的行间距  同时可以通过rotate属性设置旋转角度
 *
 * @author hailongw  fujia
 */
public class CommonTextView extends TextView {

  private static final String NAMESPACE = "http://schemas.lianjia.com/res/android";

  private static final String ATTR_ROTATE = "rotate";

  private static final int DEFAULTVALUE_DEGREES = 0;

  private int mDegrees;
  // 是否使用自定义行高，代码中设置了默认的行高，如果不设置改属性，xml设置的自定义行高无效
  private boolean mIsCustomLineSpace;

  public CommonTextView(Context context) {
    super(context);
  }

  public CommonTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setTypeface(Typeface.SANS_SERIF);

    if (attrs != null) {
      mDegrees = attrs.getAttributeIntValue(NAMESPACE, ATTR_ROTATE, DEFAULTVALUE_DEGREES);
      TypedArray typedArray =
          getContext().obtainStyledAttributes(attrs, R.styleable.CommonTextView);
      mIsCustomLineSpace =
          typedArray.getBoolean(R.styleable.CommonTextView_common_custom_lineextra, false);
      boolean isBold = typedArray.getBoolean(R.styleable.CommonTextView_common_bold, false);
      setBold(isBold);
      typedArray.recycle();
    }
  }

  /**
   * 设置是否加粗文字
   *
   * @param isBold 是否加粗
   */
  public void setBold(boolean isBold) {
    getPaint().setFakeBoldText(isBold);
  }

  /**
   * 是否使用自定义行高
   *
   * @param customLineSpace false xml中自定义的行高将失效
   */
  public void setCustomLineSpace(boolean customLineSpace) {
    mIsCustomLineSpace = customLineSpace;
  }

  @Override protected void onDraw(Canvas canvas) {

    canvas.rotate(mDegrees, getMeasuredWidth() / 2, getMeasuredHeight() / 2);
    super.onDraw(canvas);
  }

  public void setText(CharSequence text, BufferType type) {
    super.setText(text, type);
    if (!mIsCustomLineSpace) setTextViewLineExtra(this, DensityUtil.dip2px(getContext(), 5), 1);
  }

  private void setTextViewLineExtra(final TextView textView, final float add, final float mult) {
    ViewTreeObserver vto = textView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
      public void onGlobalLayout() {
        int textLine = textView.getLineCount();
        if (textLine > 0) {
          if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
          } else {
            textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
          }
          if (textLine > 1) {
            textView.setLineSpacing(add, mult);
          } else {
            textView.setLineSpacing(0, 1);
          }
        }
      }
    });
  }
}
